﻿using Framework.EncryptionDecryptionService.Enums;
using Framework.EncryptionDecryptionService.Inteface;
using Framework.EncryptionDecryptionService.Models;

namespace Framework.EncryptionDecryptionService.Abstract
{
    /// <summary>
    /// 秘钥服务抽象
    /// </summary>
    /// <remarks>
    /// <para>通过注入方式使用时加解密秘钥均为常量秘钥</para>
    /// <para>通过实例方式使用时使用自定义的秘钥</para>
    /// </remarks>
    public abstract class AbsSecretKeyService : ISecretKeyService
    {
        /// <summary>
        /// 秘钥
        /// <para>自定义秘钥</para>
        /// <para>实例方式使用</para>
        /// </summary>
        private readonly SecretKeyModel SecretKey;

        /// <summary>
        /// 常量秘钥
        /// </summary>
        /// <remarks>
        /// <para>跟随服务的整个生命周期</para>
        /// </remarks>
        internal SecretKeyModel StaticSecretKey { get; private set; }

        /// <summary>
        /// 初始化常量秘钥
        /// </summary>
        /// <returns></returns>
        internal abstract SecretKeyModel InitStaticSecretKey();

        /// <summary>
        /// 添加锁，确保静态密钥初始化线程安全
        /// </summary>
        private static readonly Lock _lock = new Lock();

        /// <summary>
        /// 秘钥服务抽象
        /// </summary>
        /// <param name="secretKey"></param>
        public AbsSecretKeyService(SecretKeyModel secretKey)
        {
            SecretKey = secretKey;
            if (StaticSecretKey == null)
            {
                lock (_lock)
                {
                    StaticSecretKey ??= InitStaticSecretKey();
                }
            }
        }

        public virtual string GetPrivateSecretKey()
        {
            return SecretKey?.PrivateSecretKey?? StaticSecretKey?.PrivateSecretKey;
        }

        public virtual string GetPublicSecretKey()
        {
            return SecretKey?.PublicSecretKey ?? StaticSecretKey?.PublicSecretKey;
        }
    }
}
